<?php
namespace app\payment\controller;

use tp5_lib\api\controller\ApiBaseController;
use app\payment\model\PaymentModel;
use tp5_lib\account\logic\AccountModule;
use tp5_lib\account\model\AccountLogModel;
use tp5_lib\user\model\UserModel;

class ApiController extends ApiBaseController
{
    /**
     * 商户收款链接
     * 用来生成收款二维码
     * 顾客端扫描二维码并根据参数调用支付接口
     */
    public function url()
    {
        $user=$this->checkLogin();
        $domain=$this->request->domain();
        $url=$domain.url("user/login/register");
        $separator = strpos("?",$url) ===false ? "?" : "&";
        $params=[
            "referral"=>$user["id"],
            "module"=>"payment",
            "action"=>"pay",
            "payee"=>$user["id"],
        ];
        $url .= $separator.http_build_query($params);
        $this->result([
            "url"=>$url,
            "qr_code"=>$domain.url("index/qrcode")."?".http_build_query(["url"=>$url]),
        ],1);
    }
    /**
     * 顾客支付
     * 扫描商户收款码付钱
     */
    public function pay()
    {
        $user=$this->checkLogin();
        $data=input();
        $model=new PaymentModel();
        $id=$model->db()->insertGetId([
            "payer"=>$user["id"],
            "payee"=>$data["payee"],
            "amount"=>$data["amount"],
            "time"=>time(),
        ]);

        if(!$way=input("way")){
            $this->error("支付方式不能为空");
        }
        $module=new AccountModule();
        if(!$config=$module->read("account")){
            $this->error("配置文件丢失");
        }
        if(empty($config["payment"][$way])){
            $this->error("未定义的支付方式");
        }
        $payment=$config["payment"][$way];
        $class=$payment["class"];
        /** @var Payment $object */
        $object=new $class;
        $params=$object->mobile("payment-$id",$data["amount"],"支付");
        $this->result(["params"=>$params],1);
    }
    /**
     * 获取统计值
     */
    public function statistics()
    {
        $user=$this->checkLogin();
        $user_model=new UserModel();
        $data=$user_model->db()->where("id",$user["id"])->find();
        
        $model=new PaymentModel();
        $data["count"]=$model->db()->whereOr([
            "payer"=>$user["id"],
            "payee"=>$user["id"],
        ])->count();//交易总笔数
        $data["pay_out"]=$model->db()->where("payer",$user["id"])->sum("amount");//总支出
        $data["earning"]=$model->db()->where("payee",$user["id"])->sum("amount");//总收入
        $this->result($data,1);
    }
    public function getPaymentRecord()
    {
        $user=$this->checkLogin();
        $model=new PaymentModel();
        $list=$model->db()->where(["payer"=>$user["id"]])->select();
        $this->result($list,1);
    }
    public function getCollectionRecord()
    {
        $user=$this->checkLogin();
        $model=new PaymentModel();
        $list=$model->db()->where(["payee"=>$user["id"]])->select();
        $this->result($list,1);
    }
    public function getRoyaltyRecord()
    {
        $user=$this->checkLogin();
        $model=new AccountLogModel();
        $list=$model->db()->where(["user_id"=>$user["id"],"type"=>"royalty"])->select();
        if($list === false){
            $this->error($model->getError());
        }
        $this->result($list,1);
    }
    /**
     * 获取用户的推荐人-包含当前用户对推荐人的分成贡献
     */
    public function referrer()
    {
        $user=$this->checkLogin();
        if(empty($user["referral"])){
            $this->result([],1,"用户没有推荐人");
        }
        $model=new UserModel();
        $sql="SELECT `user`.*,ifnull(`log`.`contrib`,0) AS `contrib` FROM `user`
        LEFT JOIN (
            SELECT `user_id`,`from`,sum(`money`) AS `contrib` FROM `account_log` AS `a`
            JOIN `payment_royalty` AS `pr` ON `pr`.`id` = `a`.`id`
            GROUP BY `user_id`,`from`
        ) AS `log` ON `log`.`from`={$user["id"]} AND `log`.`user_id`={$user["referral"]}
        WHERE `id`={$user["referral"]}";
        $record=$model->db()->query($sql);
        $data = isset($record[0]) ? $record[0] : [];
        $this->result($data,1);
    }
    /**
     * 获取用户推荐的人-包含被推荐人被当前用户的分成贡献
     */
    public function referrals()
    {
        $user=$this->checkLogin();
        $model=new UserModel();
        $sql="SELECT `user`.*,ifnull(`log`.`contrib`,0) AS `contrib` FROM `user`
            LEFT JOIN (
                SELECT `user_id`,`from`,sum(`money`) AS `contrib` FROM `account_log` AS `a`
                JOIN `payment_royalty` AS `pr` ON `pr`.`id` = `a`.`id`
                GROUP BY `user_id`,`from`
            ) AS `log` ON `log`.`from`=`user`.`id` AND `log`.`user_id`=`user`.`referral`
            WHERE `user`.`referral`={$user["id"]}";
        $record=$model->db()->query($sql);
        $this->result($record,1);
    }
}
